package tech.cn.note.word.fun;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import com.deepoove.poi.render.compute.RenderDataCompute;
import org.apache.commons.lang3.StringUtils;

import org.springframework.stereotype.Service;

import static org.springframework.util.ObjectUtils.isEmpty;

@Service
public class NumFormat implements RenderFunction {
    /**
     * @param fields            参数1 数字 参数2 可选 小数保留位数
     * @param renderDataCompute
     * @return
     */
    @Override
    public String doCalculate(String[] fields, RenderDataCompute renderDataCompute) {
        if (isEmpty(fields)) {
            return "";
        }
        String placeHolder = fields[0];
        BigDecimal numValue = (BigDecimal) renderDataCompute.compute(placeHolder);
        if (numValue == null) {
            return "";
        }
        int pointNum = 0;
        if (fields.length > 1 && fields[1] != null
                && StringUtils.isNotBlank(fields[1])) {
            pointNum = Integer.parseInt(fields[1]);
        } else {
            pointNum = numValue.scale();
        }
        return doFormat(numValue, pointNum);
    }

    public String doFormat(BigDecimal numValue, int pointNum) {
        //将数值转换位BigDecimal
        DecimalFormat decimalFormat = buildNumberFormat(pointNum);
        String format = decimalFormat.format(numValue);
        return format;
    }

    /**
     * 获取转换定义对象
     *
     * @param pointNum
     * @return
     */
    public DecimalFormat buildNumberFormat(int pointNum) {
        return new DecimalFormat(getFormatDefinition(pointNum));
    }

    /**
     * 获取转换定义格式
     *
     * @param pointNum
     * @return
     */
    public String getFormatDefinition(int pointNum) {
        StringBuffer strDefinition = new StringBuffer(getDefaultDefinition());
        if (pointNum < 1) {
            return strDefinition.toString();
        }
        strDefinition.append(".");
        for (int i = 0; i < pointNum; i++) {
            strDefinition.append("0");
        }
        return strDefinition.toString();
    }

    /**
     * 获取默认的转换定义格式
     *
     * @return
     */
    public String getDefaultDefinition() {
        return "#0";
    }

    public String removeZero(String str) {
        if (str.indexOf(".") > 0) {
            str = str.replaceAll("0+?$", "");//删掉尾数为0的字符
            str = str.replaceAll("[.]$", "");//结尾如果是小数点，则去掉
        }
        return str;
    }

    public static void main(String[] args) {
        NumFormat nf = new NumFormat();
        System.out.println(nf.doFormat(new BigDecimal("12.11111"), 3));
    }
}
